package dao

import (
	"context"
	"device-admin/internal/dal"
	"device-admin/internal/models"
)

type UpgradeVersion struct{}

// Create 创建版本
func (UpgradeVersion) Create(ctx context.Context, query *dal.Query, record models.UpgradeVersion) (string, error) {
	uv := query.UpgradeVersion
	err := uv.WithContext(ctx).Create(&record)
	return record.ID, err
}

// Update 更新版本
func (UpgradeVersion) Update(ctx context.Context, query *dal.Query, record models.UpgradeVersion) (bool, error) {
	uv := query.UpgradeVersion
	res, err := uv.WithContext(ctx).Where(uv.ID.Eq(record.ID)).Updates(&record)
	if res.RowsAffected == 1 {
		return true, nil
	} else {
		return false, err
	}
}

// Delete 删除版本
func (UpgradeVersion) Delete(ctx context.Context, query *dal.Query, ID string) error {
	uv := query.UpgradeVersion
	uv.WithContext(ctx).Where(uv.ID.Eq(ID)).Delete(&models.UpgradeVersion{})
	return nil
}

// Detail 版本详情
func (UpgradeVersion) Detail(ctx context.Context, query *dal.Query, ID string) (*models.UpgradeVersion, error) {
	uv := query.UpgradeVersion
	return uv.WithContext(ctx).Where(uv.ID.Eq(ID)).Take()
}

// List 版本列表
func (UpgradeVersion) List(
	ctx context.Context,
	query *dal.Query,
	version string,
	terminalType string,
	page, limit int,
) (
	total int64,
	records []*models.UpgradeVersion,
	err error,
) {
	uv := query.UpgradeVersion
	tx := uv.WithContext(ctx).
		Where(uv.TerminalType.Eq(terminalType))
	if version != "" {
		tx = tx.Where(uv.Version.Eq(version))
	}
	// 获取记录总数
	total, _ = tx.Count()
	// 获取版本记录
	records, err = tx.Order(uv.CreatedAt.Desc()).
		Offset(GetPageOffset(page, limit)).
		Limit(GetPageLimit(limit)).
		Find()
	// 返回结果
	return total, records, err
}
